package br.edu.unibratec.lancenet;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBar.TabListener;
import android.support.v7.app.ActionBarActivity;
import br.edu.unibratec.lancenet.DetalheFragment.PostNosFavoritos;
import br.edu.unibratec.lancenet.TimesFragment.Time;

/**
 * Classe principal da aplica��o.
 * 
 * @author Daniel, Esdras, Naftali.
 */
public class MainActivity extends ActionBarActivity implements TabListener,
		ClicouNoPost, PostNosFavoritos, Time {

	TimesFragment fragment0;
	ListPostsFragment fragment1;
	ListFavoritesPostsFragment fragment2;
	String nomeTime;

	/**
	 * Executado quando a aplicação é iniciada e instancia as View's
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		fragment0 = (TimesFragment) getSupportFragmentManager()
				.findFragmentByTag("f0");
		fragment1 = (ListPostsFragment) getSupportFragmentManager()
				.findFragmentByTag("f1");
		fragment2 = (ListFavoritesPostsFragment) getSupportFragmentManager()
				.findFragmentByTag("f2");

		if (fragment0 == null || fragment1 == null || fragment2 == null) {
			fragment0 = new TimesFragment();
			fragment1 = new ListPostsFragment();
			fragment2 = new ListFavoritesPostsFragment();

			getSupportFragmentManager().beginTransaction()
					.add(R.id.master, fragment0, "f0")
					.add(R.id.master, fragment1, "f1")
					.add(R.id.master, fragment2, "f2").commit();
		}

		// Cria a actionBar e define adiciona as abas que serão exibidas.
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.setDisplayHomeAsUpEnabled(false);

		Tab tab0 = actionBar.newTab();
		tab0.setText(getString(R.string.times));
		tab0.setTabListener(this);

		Tab tab1 = actionBar.newTab();
		tab1.setText(getString(R.string.noticias));
		tab1.setTabListener(this);

		Tab tab2 = actionBar.newTab();
		tab2.setText(getString(R.string.favoritos));
		tab2.setTabListener(this);

		actionBar.addTab(tab0);
		actionBar.addTab(tab1);
		actionBar.addTab(tab2);
		
		if (savedInstanceState != null) {
			
			// Exibe a aba salva no �ltimo estado da aplica��o.
			actionBar.setSelectedNavigationItem(savedInstanceState.getInt("tab"));
		}
	}
	
	/**
	 * Salva a aba do estado atual da aplica��o.
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
		outState.putInt("tab", getSupportActionBar().getSelectedNavigationIndex());
	}

	/**
	 * Unimplemented method
	 */
	@Override
	public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
	}

	/**
	 * Exibe o fragment correspondente � aba selecionada na ActionBar e esconde os demais fragments.
	 */
	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		if (tab.getPosition() == 0) {
			ft.show(fragment0).hide(fragment1).hide(fragment2);
		} else if (tab.getPosition() == 1) {
			ft.show(fragment1).hide(fragment0).hide(fragment2);
		} else {
			ft.show(fragment2).hide(fragment0).hide(fragment1);
		}
	}

	/**
	 * Unimplemented method
	 */
	@Override
	public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
	}

	/**
	 * Verifica e retorna verdadeiro se o dispositivo onde a aplica��o est� rodando � um Tablet.
	 * @return
	 */
	private boolean isTablet() {
		return findViewById(R.id.detail) != null;
	}

	/**
	 * Método é chamado quando um post for clicado na lista de posts ou na lista de favoritos.
	 * 
	 * Exibe o fragment de detalhe dos posts.
	 */
	@Override
	public void postFoiClicado(PostLance post) {
		
		// Se for tablet substitui o fragment de detalhe por uma instância dele mesmo.
		if (isTablet()) {
			
			DetalheFragment d = DetalheFragment.novaInstancia(post, this.nomeTime);

			getSupportFragmentManager().beginTransaction()
					.replace(R.id.detail, d).commit();
		
		} else {
			// Se for Smartphone cria uma Intent para o Detalhe activity 
			// enviando o post e o nome do time selecionado.
			Intent it = new Intent(this, DetalheActivity.class);
			it.putExtra("post", post);
			it.putExtra("nomeTime", this.nomeTime);
			startActivity(it);
		}
	}

	/**
	 * Recebe o post definido como favorito e inclui na lista de favoritos.
	 */
	@Override
	public void postAdicionadoAoFavorito(PostLance post) {
		fragment2.refreshList();
	}

	/**
	 * Recebe o link do RSS referente ao time clicado na aba 'Times',
	 * remove a lista de posts caso esteja preenchida,
	 * exibe a aba com o fragment da lista de posts e
	 * inicia o download do RSS.
	 */
	@Override
	public void clicouNoTime(String rss, String nomeTime) {
		this.nomeTime = nomeTime;
		this.fragment1.removeList();
		getSupportActionBar().setSelectedNavigationItem(1);
		this.fragment1.iniciarDownload(rss);
	}
}